//
//  BaiduLocation.m
//  BSLPlugin
//
//  Created by Fanty on 15/12/23.
//  Copyright © 2015年 Fanty. All rights reserved.
//

#import "BaiduLocation.h"

#import <BaiduMapAPI_Location/BMKLocationComponent.h>

@interface BaiduLocationPlugin()<BMKLocationServiceDelegate>
@end

@implementation BaiduLocationPlugin{
    BMKLocationService *_locService;
    BMKUserLocation* userLocation;
    int locationStatus;
}

-(void)pluginInitialize{
    locationStatus=0;
    // 创建一个定位对象
    _locService = [[BMKLocationService alloc] init];
    _locService.delegate=self;
    // 开始定位
    [_locService startUserLocationService];
    
}
- (void)stop:(CDVInvokedUrlCommand*)command{
    [_locService stopUserLocationService];
}
-(void)getCurrentPosition:(CDVInvokedUrlCommand*)command{
    NSMutableDictionary* dict=[NSMutableDictionary dictionaryWithCapacity:2];
   
    CLLocation* location=userLocation.location;
    [dict setObject:[NSNumber numberWithLongLong:[location.timestamp timeIntervalSince1970]*1000] forKey:@"time"];
//    [dict setObject:location.typ forKey:@"locType"];

    
    [dict setObject:[NSNumber numberWithDouble:location.coordinate.latitude] forKey:@"latitude"];
    [dict setObject:[NSNumber numberWithDouble:location.coordinate.longitude] forKey:@"lontitude"];
    [dict setObject:[NSNumber numberWithDouble:location.coordinate.longitude] forKey:@"radius"];
    [dict setObject:[NSNumber numberWithDouble:location.speed] forKey:@"speed"];
    [dict setObject:[NSNumber numberWithDouble:location.altitude] forKey:@"height"];
    [dict setObject:[NSNumber numberWithDouble:location.course] forKey:@"direction"];

    if(locationStatus==0)
        [dict setObject:@"正在定位中" forKey:@"describe"];
    else if(locationStatus==1)
        [dict setObject:@"网络定位成功" forKey:@"describe"];
    else if (locationStatus==2)
           [dict setObject:@"停止定位" forKey:@"describe"];
      else
        [dict setObject:@"定位失败，请检查配置" forKey:@"describe"];

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:nil];

    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];

}

#pragma mark method

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)__userLocation{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    userLocation=__userLocation;
    locationStatus=1;

}

- (void)didFailToLocateUserWithError:(NSError *)error{
    locationStatus=-1;
}



@end


